package _工具包整理._JSON转换;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Test;
import play.libs.Json;

import java.io.IOException;
import java.util.Iterator;


/**
 * 0、软件包
 *      fasterxml.jackson
 * 1、核心主体
 *      JsonNode、ObjectNode、   ArrayNode、   ObjectMapper      java对象 Json数据字符串
 * 2、常用操作
 *      JSON数据 转 JsonNode/ObjectNode
 *      自己构造、遍历、修改 ObjectNode
 *      Java 对象 转 JsonNode/ObjectNode
 *
 *          JsonNode jsonNode = objectMapper.valueToTree(Java对象);
 *          JsonNode jsonNode = mapper.convertValue(Java对象, JsonNode.class);
 *      JsonNode/ObjectNode 转 Java 对象
 */
public class ObjectNodeTest {


    public String jsonDate = "{\"username\":\"tom\",\"company\":{\"companyName\":\"中华\",\"address\":\"北京\"},\"cars\":[\"奔驰\",\"宝马\"]}";
    public String arrayJsonDate = "[{\"number\":64,\"result\":\"SUCCESS\"},{\"number\":65,\"result\":\"FAILURE\"},{\"number\":66,\"result\":\"ABORTED\"},{\"number\":67,\"result\":\"SUCCESS\"}]";

    /**
     * JSON数据 转 JsonNode          objectMapper.readTree(json)
     * 遍历 JsonNode 所有属性对
     * JSON数据 转 ObjectNode
     */
    @Test
    public void test1() throws IOException {
        System.out.println(jsonDate);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(jsonDate);
        System.out.println(jsonNode);

        Student student = new Student("liuhuan", 14, new double[]{12.34, 78.4});
        JsonNode jsonNode1 = objectMapper.valueToTree(student);
        System.out.println(jsonNode1);
    }

    /**
     * 创建一个空 json 串，添加一些属性对
     *      数组
     *      字符串
     *      double
     *
     * 遍历一个 json 串，读取 属性对，修改属性对
     *
     */
    @Test
    public void test2() {
        // get  {}
        ObjectNode objectNode = Json.newObject();
        System.out.println(objectNode);
        // set  "位置": [a, b]
        objectNode.putArray("位置").add(3.14).add(1.27);
        System.out.println(objectNode);
        // set  "name": "liuhuan"
        objectNode.put("name", "liuhuan");
        System.out.println(objectNode);
        // set  "age": 24.88
        objectNode.put("age", 24.88);
        System.out.println(objectNode);


        ArrayNode arrayNode = Json.newArray();
        arrayNode.add(objectNode);

    }


}
